<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of RestbaseController
 *
 * @author wupeng
 */
class Uuch_RestbaseController extends Zend_Controller_Action {
    //put your code here
    
    protected $_agrs = array();
    
    protected $_allowedHttpMethods = array('get', 'delete', 'post', 'put');
    
    protected $_getArgs = array();
    
    protected $_postArgs = array();
    
    protected $_putArgs = array();
    
    protected $_deleteArgs = array();
    
    protected $_restAction = null;

    public function init() {
        parent::init();
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        $method = $this->_detectMethod();
        $method = ucfirst($method);
        $this->{'_parse' . $method}();
        $request = $this->getRequest();
        $action = $request->getActionName();
        $action .= $method;
        $this->_restAction = $action . 'Action';
    }
    
    public function dispatch($action) {
        if(null != $this->_restAction){
            $action = $this->_restAction;
        }
        if(!method_exists($this, $action)){
            $action = 'noResourceAction';
        }
        return parent::dispatch($action);
    }

    public function getServer(){
        return $this->getRequest()->getMethod();
    }
    
    protected function _detectMethod()
    {
        $method = strtolower($this->getServer());

        if (in_array($method, $this->_allowedHttpMethods) && method_exists($this, '_parse' . ucfirst($method))) {
            return $method;
        }

        return 'get';
    }
    
    
    protected function _parseGet()
    {

        parse_str(parse_url($this->getServer(), PHP_URL_QUERY), $get);

        $this->_getArgs = array_merge($this->_getArgs, $get);
        $this->getRequest()->setParams($this->_getArgs);
        return $this;
    }


    protected function _parsePost()
    {
        $this->_postArgs = $this->getRequest()->getPost();
        $this->getRequest()->setPost($this->_postArgs);
        return $this;
    }

    protected function _parsePut()
    {
        parse_str(file_get_contents('php://input'), $this->_putArgs);
        $this->getRequest()->setParams($this->_putArgs);
        return $this;
    }
    
    protected function _parseDelete(){
        parse_str(file_get_contents('php://input'), $this->_deleteArgs);
        $this->getRequest()->setParams($this->_deleteArgs);
        return $this;
    }
    
    public function noResourceAction(){
        $info = array('code'=>'1006','info'=>'The required service is not available.');
        $this->getResponse()->setBody(json_encode($info));
    }
    
}
